﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Frame.Lib.Core.Cache.SysConfig;
using Frame.Lib.Core.Cache.Company;
using Frame.Lib.Core.Cache.Paras;

namespace Frame.Lib.Core.Cache
{
    public class CacheManager
    {
        private Dictionary<Type, CacheLoaderBase> _loaders;
        private Hashtable _containers;
      
        public CacheManager()
        {
            _containers = new Hashtable();
            _loaders = new Dictionary<Type, CacheLoaderBase>();

            CacheLoaderBase[] list = { new SysConfigLoader(), new CompanyLoader() ,new ParasLoader()};

            for (int i = 0; i < list.Length; i++)
            {
                _loaders.Add(list[i].GetType(), list[i]);
                list[i].LoadComplete = (container) =>
                {
                    _containers[container.GetType()] = container;
                };

                list[i].LoadData();
            }           
        }

        public CompanyContainer CompanyContainer
        {
            get
            {
                return GetContainer<CompanyContainer>();
            }
        }

        public SysConfigContainer SysConfigContainer
        {
            get
            {
                return GetContainer<SysConfigContainer>();
            }
        }

        public ParasContainer ParasContainer
        {
            get
            {
                return GetContainer<ParasContainer>();
            }
        }

        public CacheLoaderBase GetLoader(Type loadType)
        {
            if (_loaders.ContainsKey(loadType))
            {
                return _loaders[loadType];
            }
            else
            {
                return null;
            }
        }

        public T GetContainer<T>() where T:class
        {
            return _containers[typeof(T)] as T;
        }
        

        public void Update()
        {
            foreach (CacheLoaderBase loader in _loaders.Values)
            {
                loader.Update();
            }
        }

        public void Update(Type loader)
        {
            GetLoader(loader).Update();
        }

        public string GetCacheXml()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<caches>");

            foreach (object obj in _containers.Values)
            {
                sb.Append(obj.ToString());
            }

            sb.Append("</caches>");

            return sb.ToString();
        }

        private static CacheManager _instance = new CacheManager();

        public static CacheManager Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}
